package room_event

import (
	"encoding/json"
	"errors"
	"fmt"
	global2 "longmen/server/config/global"
	cache2 "longmen/server/internal/rpc/tencentim/cache"
	"longmen/server/internal/rpc/tencentim/chat"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/internal/rpc/tencentim/utils"
	"longmen/server/internal/services/consumers/publisher"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/db_live"
	"longmen/server/pkg/db/mysql/models/models_live"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
	"time"

	"longmen/server/pkg/common/api_models"
)

func handlingBanUserMessage(c *chat.ClientUser, b []byte) (result *pb.CallbackResp) {
	return setBanUser(c, b, messages2.BanUserType)
}

func handlingUnbanUserMessage(c *chat.ClientUser, b []byte) (result *pb.CallbackResp) {
	return setBanUser(c, b, messages2.UnbanUserType)
}

func setBanUser(c *chat.ClientUser, b []byte, banType int) (result *pb.CallbackResp) {
	resp := &messages2.BanUserReplyMessage{}
	resp.Type = messages2.ErrorReplyMessageType

	req := messages2.BanUserMessage{}
	err := json.Unmarshal(b, &req)
	if err != nil {
		resp.Code = 1
		resp.Message = fmt.Sprintf("invalid message struct, %s", err)
		return utils.CallbackOkResp(resp.Message)
	}
	if req.UserId <= 0 {
		resp.Code = 1
		resp.Message = fmt.Sprintf("invalid message struct, %s", err)
		return utils.CallbackOkResp(resp.Message)
	}
	global2.Log.Debugf("start ban user:%+v", req)
	var anchorId int
	anchorId = c.RoomId //在前台禁言的，总是只能禁言本房间
	banUserId := req.UserId
	err = doBanUser(&api_models.BanUserReq{
		Userid:   banUserId,
		Type:     banType,
		Anchorid: anchorId,
		BanTime:  req.BanTime, //用户被禁言的秒数
		Mgrid:    req.Mgrid,   // 操作人的id
		Reason:   req.Reason,
		BanType:  req.BanType,
		BanMsg:   req.BanMsg,
	}, req.Mgrid)

	if err != nil {
		resp.Code = 1
		resp.Message = err.Error()
		return utils.CallbackOkResp(resp.Message)
	}
	cache2.NewRoomHeat(c.RoomId).SetDec(_const.PopMsgCount, 1)
	return utils.CallbackOkResp("ok")
}

func doBanUser(r *api_models.BanUserReq, managerId int) error {
	global2.Log.Infof("banUser:%+v", r)
	var banQ messages2.BanUserChatReq
	bannerUser, err := mysql.GetUserParam(map[string]interface{}{"id": r.Userid})
	if err != nil {
		global2.Log.Errorf("bannerUser err :%v", bannerUser)
		return err
	}

	if managerId == r.Userid {
		global2.Log.Debugf("不能禁言自己 - userid:%v", r.Userid)
		return errors.New("不能禁言自己")
	}
	if r.Anchorid == r.Userid {
		global2.Log.Debugf("不能禁言主播 - userid:%v", r.Anchorid)
		return errors.New("不能禁言主播")
	}
	//global.Log.Debugf("doBanUser :%v", r)
	managerUser, err := db_live.GetLiveRoomManagerParam(map[string]interface{}{"mgrid": managerId})
	if err != nil {
		return err
	}
	if r.Mgrid != r.Anchorid && managerId != r.Anchorid && managerUser.Id < 1 {
		global2.Log.Errorf("您没有权限操作:%d", r.Userid)
		return errors.New("您没有权限操作")
	}
	global2.Log.Debugf("禁言类型:%d", r.Type)
	banQ.UserId = bannerUser.Id
	banQ.NickName = bannerUser.NickName
	banQ.TBan = r.BanTime
	if r.Type == messages2.BanUserType { //禁言
		banQ.BanType = messages2.BanUserType
		err = AddBanRecord(r.Userid, r.Anchorid, managerId, r.BanType, r.BanTime, r.Reason, r.BanMsg)
		if err != nil {
			return errors.New("插入禁言记录失败")
		}
	} else {
		banQ.BanType = messages2.UnbanUserType
		banQ.TBan = 0
		err := global2.Live().Where("anchorid=? and uid=?", r.Anchorid, r.Userid).Delete(&models_live.LiveRoomBanneduser{}).Error
		if err != nil {
			return errors.New("解除失败")
		}
	}
	cache.DelBannerListCache(r.Anchorid)
	//______________组装管理员记录______________
	oAdminLog := &models_main.AdminLog{}
	oAdminLog.Uid = uint(r.Userid)
	oAdminLog.CreateTime = time.Now()
	oAdminLog.Mgrid = managerId
	sVerb := "解禁"
	sTail := ""
	if r.BanTime != 0 {
		sVerb = "禁言"
		if len(r.Reason) > 0 {
			sTail = sTail + fmt.Sprintf(",原因:%s", r.Reason)
		}
		if len(r.BanMsg) > 0 {
			sTail = sTail + fmt.Sprintf(",发言:%s", r.BanMsg)
		}
	}
	sMsg := fmt.Sprintf("%d在前台%s用户%d%s", r.Mgrid, sVerb, r.Userid, sTail)
	oAdminLog.Content = sMsg
	//cache.PushAny(oAdminLog, messages.AdminLogChannel) //异步插入管理员操作记录
	global2.PublisherTxChat.BroadCast(publisher.AdminLog, oAdminLog)
	//------------------------------------------------------^^^^^^^^^^^^^^
	var req messages2.BanUserChatReq
	req.TBan = banQ.TBan
	req.UserId = banQ.UserId
	req.NickName = banQ.NickName
	req.BanType = banQ.BanType
	req.RoomId = r.Anchorid
	req.BanMsg = r.BanMsg
	req.Reason = r.Reason
	return BanUserGroup(&req)
}
func AddBanRecord(userid, anchorid, mgrid, banType int, tBan int64, reason, banMsg string) error {
	liveRoomBanneduser := &models_live.LiveRoomBanneduser{ //--------------------入库的数据
		Uid: userid, Anchorid: anchorid, Mgrid: mgrid,
		CreateTime: time.Now(),
		BanTime:    tBan + time.Now().Unix(),
		Reason:     reason,
		BanType:    banType,
		BanMsg:     banMsg,
		AdminId:    0}
	//查看是否重复禁言
	var check int64
	err := global2.Live().Model(&models_live.LiveRoomBanneduser{}).
		Where("uid=? and (anchorid=0 or anchorid=?) and (ban_time=0 or ban_time>?)",
			userid, anchorid, time.Now().Unix()).Count(&check).Error
	if err != nil {
		global2.Log.Warnf("GetLiveRoomBanneduserParam:%v", err)
		return err
	}
	if check > 0 {
		global2.Log.Infof("不要重复禁言:%d", userid)
		return errors.New("用户已被禁言")
	}

	global2.Log.Debugf(" ==== 插入禁言表 ==== ", "Uid: ", userid, "   Anchorid:", anchorid,
		" Mgrid: ", mgrid, "  CreateTime: ", time.Now(), "    BanTime: ", tBan)

	err = db_live.InsertLiveRoomBanneduser(liveRoomBanneduser)
	if err != nil {
		global2.Log.Errorf("InsertLiveRoomBanneduser:%v", err)
		return err
	}
	return nil
}

func DoBanUser(req *api_models.BanUserReq, managerId int) error {
	return doBanUser(req, req.Mgrid)
}
